package lew.bing.novels;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by 刘国兵 on 2019/8/18.
 *
 * @author 刘国兵
 */
public class DefaultCollectNovels implements CollectNovels{



    private NovelLoader novelLoader;

    private ThreadPoolExecutor executor =
            new ThreadPoolExecutor(4, 100, 1, TimeUnit.SECONDS,
                    new LinkedBlockingQueue<>(), new ThreadFactory() {
                private AtomicInteger i = new AtomicInteger(1);
                @Override
                public Thread newThread(Runnable r) {
                    Thread thread = new Thread(r);
                    thread.setName(String.format("collect novels %d", i.getAndIncrement()));
                    thread.setDaemon(false);
                    return thread;
                }
            });

    public DefaultCollectNovels(NovelLoader novelLoader) {
        this.novelLoader = novelLoader;
    }



    @Override
    public List<Novel> collect(long timeout, TimeUnit timeUnit) {
        List<String> addresses = novelLoader.addresses();
        Novel[] novels = new Novel[addresses.size()];
        CountDownLatch countDownLatch = new CountDownLatch(addresses.size());
        for (int i = 0; i < addresses.size(); i++) {
            int j = i;
            Runnable task = () -> {
                Novel novel = novelLoader.getNovel(j);
                System.out.println("下载完"+j+"张");
                novels[j] = novel;
                countDownLatch.countDown();
            };
            executor.execute(task);
        }
        try {
            if (timeout <= 0) {
                countDownLatch.await();
            } else {
                countDownLatch.await(timeout, timeUnit);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        executor.shutdownNow();
        return Arrays.asList(novels);
    }

}
